package shmged.com.shlcm.utils;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;

import wt.httpgw.URLFactory;
import wt.inf.container.WTContained;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.session.SessionServerHelper;
import wt.util.WTContext;
import wt.util.WTProperties;

/**
 * 
 * 
 * 
 */
public class CmJSPBasic implements RemoteAccess {
    public static final String CRLF = "\r\n";
    
    protected PageContext pageContext;
    protected HttpSession session;
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected PrintWriter out = null;
 
    protected CmJSPBasic(PageContext pc) throws UnsupportedEncodingException {
        this(pc, true);
    }
    
    protected CmJSPBasic(PageContext pc, boolean getWriter) throws UnsupportedEncodingException {
        pageContext = pc;
        session = pc.getSession();
        request = (HttpServletRequest) pc.getRequest();
        request.setCharacterEncoding("gbk");
        response = (HttpServletResponse) pc.getResponse();
        if (getWriter)
            out = new PrintWriter(pageContext.getOut(), true);
        getLocalizedMessages();
    }
    
    public void getCSSLink() throws Exception {
        WTProperties wtp = WTProperties.getLocalProperties();
        String csss = wtp.getProperty("solutions.stylesheet", "");
        String[] css = csss.split(",");
        URLFactory uf = new URLFactory();
        for (int i = 0; i < css.length; i++) {
            if (css[i].equals(""))
                continue;
            String url = uf.getHREF(css[i]);
            if (out != null)
                out.println("<link rel='stylesheet' type='text/css' href='" + url + "'>");
        }
    }
    
    public void getInputButton(String name, String value, String onClick, String id) throws Exception {
        StringBuffer buf = new StringBuffer();
        buf.append("<input type='button' class='wizBtn' ");
        buf.append("name='").append(name).append("' ");
        buf.append("value='").append(value).append("' ");
        if (id != null && !id.equals(""))
            buf.append("id='").append(id).append("' ");
        if (onClick != null && !onClick.equals(""))
            buf.append("onClick='").append(onClick).append("' ");
        buf.append(">");
        if (out != null)
            out.println(buf);
    }
    
    public void getWizardHeader(String title) throws Exception {
        getWizardHeader(title, null);
    }
    
    public void getWizardHeader(String title, String help) throws Exception {
        URLFactory uf = new URLFactory();
        String sp = "<img src='" + uf.getHREF("netmarkets/images/sp.gif", true) + "'>";
        help = ein(help);
        StringBuffer html = new StringBuffer();
        html.append("<TABLE width='100%' border=0 cellpadding=0 cellspacing=0>" +
            "<TR>" +
            "  <td colspan='2' height='1'></td>" +
            "  <td class='wizOutline' width='100%' height='1'>").append(sp).append("</td>" +
            "  <td colspan='2' height='1'></td>" +
            "</TR><TR>" +
            "  <td width='1' height='1'>").append(sp).append("</td>" +
            "  <td class='wizOutline' width='1'>").append(sp).append("</td>" +
            "  <td class='wizTitle' width='100%'>").append(sp).append("</td>" +
            "  <td class='wizOutline' width='1'>").append(sp).append("</td>" +
            "  <td width='1'>").append(sp).append("</td>" +
            "</TR><TR>" +
            "  <td class='wizOutline' width='1'></td>" +
            "  <td class='wizTitle' width='1'></td>" +
            "  <TD class='wizTitle' valign='center' width='100%' nowrap>" +
            "    <TABLE width='100%' border=0 cellpadding=0 cellspacing=0>" +
            "      <TR>" +
            "        <TD class=wizTitle align=left valign=center>&nbsp;").append(title).append("</TD>" +
            "        <TD class=wizTitle valign=center align=right>" +
            "          <TABLE cellpadding=1 cellspacing=1>" +
            "            <TR><TD></TD>").append(
                        (help == null || help.equals("") ?
            "            <TD><TR><TD colspan=2></TD>" :
            "            <TD class=hlpBg><TR><TD></TD><TD class=hlpBg>" + help + "</TD></TR>") + 
            "          </TABLE>" +
            "        </td>" +
            "      </tr>" +
            "    </table>" +
            "  </TD>" +
            "  <td class='wizTitle' width='1'>").append(sp).append("</td>" +
            "  <td class='wizOutline' width='1'>").append(sp).append("</td>" +
            "</TR><TR>" +
            "  <td width='1' height='1'>").append(sp).append("</td>" +
            "  <td class='wizOutline' width='1'>").append(sp).append("</td>" +
            "  <td class='wizTitle' width='100%'>").append(sp).append("</td>" +
            "  <td class='wizOutline' width='1'>").append(sp).append("</td>" +
            "  <td width='1'>").append(sp).append("</td>" +
            "</TR><TR>" +
            "  <td colspan='2' height='1'></td>" +
            "  <td class='wizOutline' width='100%' height='1'>").append(sp).append("</td>" +
            "  <td colspan='2' height='1'></td>" +
            "</tr>" +
            "</TABLE>");
        if (out != null)
            out.println(html);
    }
    
    public static String getCalendarPickerCode() throws Exception {
        return getCalendarPickerCode(false);
    }
    
    public static String getCalendarPickerCode(boolean withMainLink) throws Exception {
        URLFactory uf = new URLFactory();
        String script1 = uf.getHREF("wtcore/js/com/ptc/core/ca/web/misc/main.js", true);
        String script2 = uf.getHREF("wtcore/js/com/ptc/core/ca/web/misc/trlUtils.js", true);
        String script3 = uf.getHREF("wtcore/js/com/ptc/core/ca/web/misc/calendar.js", true);
        
        StringBuffer sbuf=new StringBuffer();
        if (withMainLink) {
            sbuf.append("<SCRIPT Language='javascript' src='" + script1 + "'></SCRIPT>\n");
            sbuf.append("<SCRIPT Language='javascript' src='" + script2 + "'></SCRIPT>\n");
            sbuf.append("<SCRIPT Language='javascript' src='" + script3 + "'></SCRIPT>\n");
        }
        sbuf.append("<SCRIPT Language=\"JavaScript\">").append("\n");
        sbuf.append("//dcaInitDatePos(3,2,1);").append("\n");
        sbuf.append("function newWindow(screenX, screenY, url, moreUrlInfo) {").append("\n");
        sbuf.append("   var properties = \"\";").append("\n");
        sbuf.append("    if ((screenX + 240) > (screen.width)) {").append("\n");
        sbuf.append("        properties = \"left=\" + (screenX - 260);}").append("\n");
        sbuf.append("    else {").append("\n");
        sbuf.append("       properties = \"left=\" + (screenX + 20);}").append("\n");
        sbuf.append("    if ((screenY + 220) > (screen.height)) {").append("\n");
        sbuf.append("        properties += \",top=\" + (screenY - 220);}").append("\n");
        sbuf.append("    else {").append("\n");
        sbuf.append("        properties += \",top=\" + (screenY + 1);}").append("\n");
        sbuf.append("    properties += \",dependent=1,titlebar=0,resizable=1,\";").append("\n");
        sbuf.append("    properties += moreUrlInfo + \", location=0, fullscreen=0, channelmode=0,directories=0, menubar=0,scrollbars=0, status=0,toolbar=0\";").append("\n");
        sbuf.append("    myCalendarWindow=wfWindowOpen(url,'cal',properties);").append("\n");
        sbuf.append("}").append("\n");
        sbuf.append("function pickDate(evnt, thisField) {\n");
        sbuf.append("    var name = thisField.getAttribute(\"target_id\");\n");
        sbuf.append("    var fields = document.getElementsByName(name);\n");
        sbuf.append("    var field = fields[0];\n");
        sbuf.append("    for (var i = 0; i < fields.length; i++) {\n");
        sbuf.append("        if (fields[i].parentNode == thisField.parentNode) {\n");
        sbuf.append("            field = fields[i]; break;\n");
        sbuf.append("        }\n");
        sbuf.append("    }\n");
        sbuf.append("    pickCalendar(field, evnt.screenX, evnt.screenY);\n");
        sbuf.append("}\n");
        boolean cn = WTContext.getContext().getLocale().equals(Locale.PRC);
        sbuf.append("function pickCalendar(field, screenX, screenY) {").append("\n");
        //unicode is://'��������ѡ������'
        if (cn)
            sbuf.append("   initCal('\u5728\u65e5\u5386\u4e0a\u9009\u62e9\u65e5\u671f',").append("\n");
        else
            sbuf.append("   initCal('Please select date',").append("\n");
        sbuf.append("           '<LINK REL=stylesheet HREF=\"");
        sbuf.append(uf.getHREF("wtcore/css/com/ptc/core/ca/web/misc/DCAcal.css", true));
        sbuf.append("\" TYPE=\"text/css\">',").append("\n");
        sbuf.append("'").append(uf.getHREF("wtcore/js/com/ptc/core/ca/web/misc/trlUtils.js", true)).append("',").append("\n");
        sbuf.append("           3, 2, 1, 'null', 'null', false, 10, ");
        sbuf.append((new Date()).getYear()+1900-2).append(");").append("\n");
        sbuf.append("   setDateField(field, 'yyyy/MM/dd',").append("\n"); 
        sbuf.append("        '1 #2 #3 #4 #5 #6 #7 #8 #9 #10#11#12#','#',").append("\n");
        //unicode is:'������#����һ#���ڶ�#������#������#������#������#'
        if (cn)
            sbuf.append("        '\u661f\u671f\u65e5#\u661f\u671f\u4e00#\u661f\u671f\u4e8c#\u661f\u671f\u4e09#\u661f\u671f\u56db#\u661f\u671f\u4e94#\u661f\u671f\u516d#', '0');").append("\n");
        else
            sbuf.append("        'Mon#Tue#Wed#Thu#Fri#Sat#Sun#', '0');").append("\n");
        sbuf.append("   newWindow(screenX, screenY, '");
        sbuf.append(uf.getHREF("wtcore/jsp/com/ptc/core/ca/web/property/date/calPopup.jsp", true));
        sbuf.append("', 'height=240,width=240');").append("\n");
        sbuf.append("   return false;").append("\n");
        sbuf.append("}").append("\n");
        sbuf.append("</SCRIPT>").append("\n"); 
        return sbuf.toString();
    }
    
    public static String getDateChecker() {
        StringBuffer ss = new StringBuffer();
        ss.append("<script language=javascript>\r\n");
        ss.append("function checkDate(sdate) {\r\n");
        ss.append("   var re = new RegExp('^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})$', '');\r\n");
        ss.append("   if (re.exec(sdate) == null)\r\n");
        ss.append("       return false;\r\n");
        ss.append("   var y = parseInt(RegExp.$1, 10);\r\n");
        ss.append("   var m = parseInt(RegExp.$2, 10);\r\n");
        ss.append("   var d = parseInt(RegExp.$3, 10);\r\n");
        ss.append("   if (y < 1 || m < 1 || d < 1)\r\n");
        ss.append("      return false;\r\n");
        ss.append("   if ((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) && d <= 31)\r\n");
        ss.append("      return true;\r\n");
        ss.append("   if ((m == 4 || m == 6 || m == 11) && d <= 30)\r\n");
        ss.append("      return true;\r\n");
        ss.append("   if (m == 2 && d <= 29 && y % 4 == 0)\r\n");
        ss.append("      return true;\r\n");
        ss.append("   if (m == 2 && d <= 28)\r\n");
        ss.append("      return true;\r\n");
        ss.append("   return false;\r\n");
        ss.append("}\r\n");
        ss.append("</script>\r\n");
        return ss.toString();
    }
    
    public static String ein(Object s) {
        return s == null ? "" : String.valueOf(s);
    }
    
    public static String ein(Object s, String def) {
        if (s == null || s.equals("")) {
            return def == null ? "" : def;
        }
        return String.valueOf(s);
    }
    
    public static String[] ein(String[] ss) {
        if (ss == null)
            return new String[0];
        for (int i = 0; i < ss.length; i++)
            if (ss[i] == null)
                ss[i] = "";
        return ss;
    }
    
    public static boolean eon(Object o) {
        if (o == null || "".equals(o))
            return true;
        return false;
    }
    
    public static String nbsp(Object s) {
        if (s == null || s.equals(""))
            s = "&nbsp;";
        return String.valueOf(s);
    }
    
    public static String conv(String s) {
        if (s == null)
            return s;
        try {
            return new String(s.getBytes("iso-8859-1"), "utf-8");
        }
        catch (UnsupportedEncodingException e) {
            return s;
        }
    }
    
    public static String[] conv(String[] ss) {
        if (ss == null)
            return new String[0];
        for (int i = 0; i < ss.length; i++) {
            try {
                ss[i] = new String(ss[i].getBytes("iso-8859-1"), "utf-8");
            }
            catch (UnsupportedEncodingException e) {
            }
        }
        return ss;
    }
    
    protected static Integer parseInt(String val) {
        try {
            return new Integer(Integer.parseInt(val));
        }
        catch (Exception e) {
            return null;
        }
    }
    
    protected static int parseIntValue(String val) {
        try {
            return Integer.parseInt(val);
        }
        catch (Exception e) {
            return 0;
        }
    }
    
    protected static String linkSort(String label, String key, String currentKey) {
        StringBuffer s = new StringBuffer();
        s.append("<a href=\"javascript:do_sort('" + key + "');\"");
        if (key.equals(currentKey))
            s.append(" style='color:#FFFFFF'");
        s.append(">").append(label).append("</a>");
        return s.toString();
    }
    
    protected static String linkGoto(int page) {
        StringBuffer s = new StringBuffer();
        s.append("<a href=\"javascript:goto_page(").append(page).append(");" +
                "\">&nbsp;");
        if (page < 10)
            s.append("0");
        s.append(page).append("&nbsp;</a>");
        return s.toString();
    }
    
    protected static String linkPages(int page, int size, int pageSize) {
        int pages = (size + pageSize - 1) / pageSize;
        int pageFrom = page - 10 <= 0 ? 1 : page - 10;
        int pageTo = page + 10 > pages ? pages : page + 10;
        StringBuffer s = new StringBuffer();
        if (pageFrom > 1)
            s.append(linkGoto(1)).append("...");
        for (int i = pageFrom; i <= pageTo; i++) {
            if (i == page) {
                String ss = i < 10 ? "0" + i : String.valueOf(i);
                s.append("<b style='background-color:#EEEEEE'>&nbsp;").append(ss).append("&nbsp;</b>");
            }
            else
                s.append(linkGoto(i));
        }
        if (pageTo < pages)
            s.append("...").append(linkGoto(pages));
        return s.toString();
    }
    
    public Locale locale = WTContext.getContext().getLocale();
    public String _T(String cnString, String enString) {
        if (Locale.SIMPLIFIED_CHINESE.equals(locale))
            return cnString;
        return enString;
    }
    
    public static String _T(Locale lc, String cnString, String enString) {
        if (Locale.PRC.equals(lc))
            return cnString;
        return enString;
    }
    
    public boolean zh_CN() {
        return Locale.SIMPLIFIED_CHINESE.equals(locale);
    }
    
    public void getLocalizedMessages() {
    }
    

    

    
    public static String encodeProjectNumbers(List nums) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < nums.size(); i++) {
            if (buf.length() > 0)
                buf.append("/");
            buf.append(nums.get(i));
        }
        return buf.toString();
    }
    
    public static String getContainerName(WTContained contained) throws Exception {
        if (!RemoteMethodServer.ServerFlag) {
            return (String) RemoteMethodServer.getDefault().invoke("getContainerName",
                    CmJSPBasic.class.getName(), null,
                    new Class[]{WTContained.class}, new Object[]{contained});
        }
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
        try {
            return contained.getContainer().getName();
        }
        finally {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
    }
    
    public static WTContainer getContainer(WTContainerRef contRef) throws Exception {
        if (!RemoteMethodServer.ServerFlag) {
            return (WTContainer) RemoteMethodServer.getDefault().invoke("getContainer",
                    CmJSPBasic.class.getName(), null,
                    new Class[]{WTContainerRef.class}, new Object[]{contRef});
        }
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
        try {
            return contRef.getReferencedContainer();
        }
        finally {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
    }
}
